package com.cj.sbs.config.shiro.realm;

import com.cj.sbs.config.shiro.JWTToken;
import com.cj.sbs.po.User;
import com.cj.sbs.service.UserService;
import com.cj.sbs.util.JWTUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;

/**
 * ClassName: SbsShiroRealm <br/>
 * Function: sbs shiro realm <br/>
 * date: 2018/04/24 17:06 <br/>
 *
 * @author chenj
 * @version 1.0.0
 * @since JDK 1.8
 */
@Component
public class SbsShiroRealm extends AuthorizingRealm {

    private static final Logger LOGGER = LoggerFactory.getLogger(SbsShiroRealm.class);

    @Resource
    private UserService userService;

    /**
     * 必须重写此方法，不然Shiro会报错
     *
     * @param token
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 角色权限和对应权限
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userName = JWTUtil.getUsername(principalCollection.toString());
        LOGGER.info("配置权限，从数据库获取");
        List<String> roles = userService.queryRolesByUserName(userName);
        List<String> permissions = userService.queryPermissionsByUserName(userName);

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(new HashSet<>(roles));
        simpleAuthorizationInfo.setStringPermissions(new HashSet<>(permissions));
        return simpleAuthorizationInfo;
    }

    /**
     * 用户认证
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        if (authenticationToken.getCredentials() == null) {
            throw new AuthenticationException("token invalid");
        }
        String token = authenticationToken.getCredentials().toString();
        String userName = JWTUtil.getUsername(token);
        if (StringUtils.isEmpty(userName)) {
            throw new AuthenticationException("token invalid");
        }
        User user = userService.selectByUserName(userName);
        if (user == null) {
            throw new AuthenticationException("user didn't existed");
        }
        if (!JWTUtil.verify(token, userName, user.getPassword())) {
            throw new AuthenticationException("username or password error");
        }
        return new SimpleAuthenticationInfo(token, token, getName());
    }
}
